//
//  FQDSubscribeManager.m
//  FakeQDaily
//
//  Created by mewxiv on 9/22/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDSubscribeManager.h"
#import "FQDAccountManager.h"
#import "FQDRestModel.h"
#import "QDailyAPI.h"

#import "FQDRegisterNavViewController.h"
#import "MBProgressHUD+FQDExtension.h"

#import "YYModel.h"

@interface FQDSubscribeManager ()

@property (nonatomic, readwrite, strong) NSArray *allColumns;

@end

@implementation FQDSubscribeManager

+ (void)load
{
    __weak typeof(self) wself = self;
    __block id observer =
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidFinishLaunchingNotification
     object:nil queue:[NSOperationQueue mainQueue]
     usingBlock:^(NSNotification * _Nonnull note) {
         typeof(self) sself = wself;
         [sself sharedManager];
         [[NSNotificationCenter defaultCenter] removeObserver:observer
          name:UIApplicationDidFinishLaunchingNotification
          object:nil];
    }];
}

+ (instancetype)sharedManager
{
    static FQDSubscribeManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self class] new];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupNotifications];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupNotifications
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(userAccountDidChangeNotification:)
                          name:FQDAccountUserInfoDidChangeNotification object:nil];
}

#pragma mark - Public methods
- (void)getAllSubscribeColumns:(NSString *)userId completion:(void (^)(BOOL success))completion
{
    [[QDailyAPI sharedAPI] getUserSubscription:userId completion:^(id responseObject, NSError *error) {
        if (responseObject) {
            NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
            if ([status integerValue] == 200) {
                id response = responseObject[@"response"];
                self.allColumns = [NSArray yy_modelArrayWithClass:[FQDColumn class]
                                                             json:response[@"columns"]];
                
                [self postSubscribeColumnsDidChangeNotification];
                completion ? completion(YES) : nil ;
            } else {
                NSString *msg = [responseObject valueForKeyPath:@"meta.msg"];
                FQDLog(@"Cannot get subscribe columns:%@", [msg description]);
                completion ? completion(NO) : nil;
            }
        } else {
            FQDLog(@"Cannot get subscribe columns:%@", [error localizedDescription]);
            completion ? completion(NO) : nil;
        }
    }];
}

- (void)addSubscribeColumn:(NSString *)columnId completion:(void (^)(BOOL success))completion
{
    [[QDailyAPI sharedAPI] addSubscribeColumn:columnId completion:^(id responseObject, NSError *error) {
        NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
        if ([status integerValue] == 200) {
            id response = responseObject[@"response"];
            FQDColumn *column = [FQDColumn yy_modelWithJSON:response];
            NSMutableArray *mutableColumns = [self.allColumns mutableCopy];
            FQDColumn *oldColumn = [self columnForColumnId:columnId];
            [mutableColumns removeObject:oldColumn];
            [mutableColumns addObject:column];
            self.allColumns = [mutableColumns copy];
            
            [self postSubscribeColumnsDidChangeNotification];
            completion ? completion(YES) : nil ;
        } else {
            completion ? completion(NO) : nil;
        }
    }];
}

- (void)removeSubscribeColumn:(NSString *)columnId completion:(void (^)(BOOL success))completion
{
    [[QDailyAPI sharedAPI] removeSubscribeColumn:columnId completion:^(id responseObject, NSError *error) {
        NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
        if ([status integerValue] == 200) {
            NSMutableArray *mutableColumns = [self.allColumns mutableCopy];
            FQDColumn *oldColumn = [self columnForColumnId:columnId];
            [mutableColumns removeObject:oldColumn];
            self.allColumns = [mutableColumns copy];
            
            [self postSubscribeColumnsDidChangeNotification];
            completion ? completion(YES) : nil ;
        } else {
            completion ? completion(NO) : nil;
        }
    }];
}

- (void)toggleSubscribeColumn:(NSString *)columnId completion:(void (^)(BOOL success, BOOL subscribed))completion;
{
    BOOL isLogined = [[FQDAccountManager sharedManager] isLogined];
    if (!isLogined) {
        UINavigationController *navController = (UINavigationController *)
        [UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *topVC = [navController topViewController];
        FQDRegisterNavViewController *registerVC = [[FQDRegisterNavViewController alloc] init];
        registerVC.backgroundViewController = topVC;
        [topVC presentViewController:registerVC animated:YES completion:nil];
        [MBProgressHUD showMessage:@"请先登录"];
        return;
    }
    
    FQDSubscribeManager *subscribeManager = [FQDSubscribeManager sharedManager];
    BOOL hasSubscribe = [subscribeManager hasSubscribedColumn:columnId];
    NSString *const kSubscribeSuccessImageName = @"subscribeSuccess";
    NSString *const kUnSubscribeSucessImageName = @"unSubscribeSuccess";
    NSString *successImageName = (hasSubscribe) ? kUnSubscribeSucessImageName : kSubscribeSuccessImageName;
    if (!hasSubscribe) {
        [subscribeManager addSubscribeColumn:columnId completion:^(BOOL success) {
            if (success) {
                UIImage *sucessImage = [UIImage imageNamed:successImageName];
                [MBProgressHUD showImage:sucessImage];
            }
            BOOL subscribed = (success) ? YES : NO;
            completion ? completion(success, subscribed) : nil;
        }];
    } else {
        [subscribeManager removeSubscribeColumn:columnId completion:^(BOOL success) {
            if (success) {
                UIImage *sucessImage = [UIImage imageNamed:successImageName];
                [MBProgressHUD showImage:sucessImage];
            }
            BOOL subscribed = (success) ? NO : YES;
            completion ? completion(success, subscribed) : nil;
        }];
    }
}

- (FQDColumn *)columnForColumnId:(NSString *)columnId
{
    FQDColumn *resultColumn = nil;
    for (FQDColumn *column in self.allColumns) {
        if ([column.ID isEqualToString:columnId]) {
            resultColumn = column;
            break;
        }
    }
    return resultColumn;
}

- (BOOL)hasSubscribedColumn:(NSString *)columnId
{
    return ([self columnForColumnId:columnId] != nil);
}

- (BOOL)hasSubscribedAnyColumn
{
    return [self.allColumns count] > 0;
}

#pragma mark - Private methods

- (void)postSubscribeColumnsDidChangeNotification
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter postNotificationName:FQDSubscribeColumnsDidChangeNotification object:self];
}

- (NSArray *)allColumns
{
    if (!_allColumns) {
        _allColumns = [NSArray array];
    }
    return _allColumns;
}

#pragma mark - Notifications
- (void)userAccountDidChangeNotification:(NSNotification *)note
{
    FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
    if ([accountManager isLogined]) {
        FQDUser *user = accountManager.currentUser;
        [self getAllSubscribeColumns:user.userId completion:nil];
    } else {
        self.allColumns = [NSArray array];
        [self postSubscribeColumnsDidChangeNotification];
    }
}

@end
